package com.forn6.n6_bt_ringbell;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity{
	private BluetoothAdapter mAdapter=BluetoothAdapter.getDefaultAdapter();
	private NumDB num =new NumDB(this);
	private SimpleCursorAdapter adapter;
	private Cursor c;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ListView listView = (ListView) findViewById(R.id.listNum);
		SQLiteDatabase db = num.getReadableDatabase();
		
		String[] columnsDB = {
				NumDBSchema.Num._ID,
				NumDBSchema.Num.COLUMN_NAME_NUM
			    };

		c = db.query(
			NumDBSchema.Num.TABLE_NAME,  // The table to query
			columnsDB,                               // The columns to return
		    null,                                // The columns for the WHERE clause
		    null,                            // The values for the WHERE clause
		    null,                                     // don't group the rows
		    null,                                     // don't filter by row groups
		    null                                 // The sort order
		    );
		
		String[] fromColumns = {
				NumDBSchema.Num.COLUMN_NAME_NUM
			    };
		int[] toViews = {android.R.id.text1};
		adapter = new SimpleCursorAdapter(this.getApplicationContext(), 
		        R.layout.num_row, c, fromColumns, toViews);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		listView.setAdapter(adapter);
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu, menu);
		return true;
	}
	
	public void onToggleClicked(View view) {
	    // Is the toggle on?
	    boolean on = ((ToggleButton) view).isChecked();
	    
	    if (on) {
	    	//check if MAC address is correct
	    	EditText macForm = (EditText) findViewById(R.id.editText1);
	    	String mac = macForm.getText().toString();
	    	System.out.println("mac entered : "+mac);
	    	//if not correct, display an error and toggle off the button
	    	if(!BluetoothAdapter.checkBluetoothAddress(mac)){
	    		displayToast(getResources().getText(R.string.mac_address_not_valid));
	    		((ToggleButton) view).setChecked(false);
	    	}
	    	//if mac is correct
	    	else{
		    	//setup device with MAC address
		    	boolean init = initBluetoothDevice(mac);
		    	System.out.println("device init finished");
		    	if(init){
		    		//start watching connections
			    	dumpBtEv = new Thread(dumpBtEvR);
			    	dumpBtEv.start();
		    	}
		    	else{
		    		System.out.println("Error init bluetooth device");
		    		displayToast(getResources().getText(R.string.mac_address_not_valid));
		    		((ToggleButton) view).setChecked(false);
		    	}
	    	}
	    	
	    } else {//if toggle button is turned off, stop watching
	    	isWatching = false;
	    	dumpBtEv = null;
	    	TextView connection = (TextView) findViewById(R.id.textView2);
			connection.setText("");
			//mAdapter.disable();
	    }
	}
	
	public void addNum(View view){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    LayoutInflater inflater = getLayoutInflater();
	    
	    final View addNumView = inflater.inflate(R.layout.num_add, null);
	    final TextView addNumEntry = (EditText) addNumView.findViewById(R.id.add_phone_num);
	    
		builder.setMessage(R.string.add_num)
	           .setTitle(R.string.add_num_title)
		       .setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	   System.out.println("entry : "+addNumEntry.getText().toString());
	        	   addToDB(addNumEntry.getText().toString());
	           }
	       })
		       .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	               // User cancelled the dialog
	           }
	       })
		
		       .setView(addNumView);
		
		AlertDialog dialog =  builder.create();
		dialog.show();
		
	}
	
	public void addToDB(String numero){
		SQLiteDatabase dbW = num.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(NumDBSchema.Num.COLUMN_NAME_NUM, numero);
		dbW.insert(
				NumDBSchema.Num.TABLE_NAME,
		         NumDBSchema.Num.COLUMN_NAME_NUM,
		         values);
		c.requery();
		adapter.notifyDataSetChanged();
	}
	
	public void removeNum(View view){
		ListView list = (ListView)findViewById(R.id.listNum);
		SQLiteDatabase dbW = num.getWritableDatabase();
		for(long i:list.getCheckedItemIds()){
			System.out.println("suppr: "+i);
			String selection = NumDBSchema.Num._ID + " LIKE ?";
			String[] selectionArgs = { String.valueOf(i) };
			dbW.delete(NumDBSchema.Num.TABLE_NAME, selection, selectionArgs);
		}
		c.requery();
		adapter.notifyDataSetChanged();
		
	}

	//instantiate an Handler to take care of messages returned by watching thread
	private Handler messageHandler = new Handler() {
	
		public void handleMessage(Message msg) {
		super.handleMessage(msg);
		TextView connection = (TextView) findViewById(R.id.textView2);
		String btad = extractBdAddr((String)msg.getData().get("bdaddr"));
		connection.setText("CONNEXION DE "+btad);
		connection.setTextColor(Color.RED);
		// TODO : Send SMS
		}
	};
	//isWatching control the thread (run or stop)
	boolean isWatching = false;
	Thread dumpBtEv;
	Runnable dumpBtEvR = new Runnable() {
		@Override
		public void run() {
			isWatching = true;
			//bash script to launch to watch connections
			String cmd = "sh /data/local/tmp/dump_bt_ev.sh";
	    	Process process;
			try {
				//getting su
				process = Runtime.getRuntime().exec("su");
				//getting stin to write command in su shell
				DataOutputStream  stream=new DataOutputStream(process.getOutputStream());
				stream.writeBytes(cmd+"\n");
				//getting stout to catch messages
		    	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
	
		    	Bundle log = new Bundle();
		    	String line;
				while (isWatching)
				 {
				  line = bufferedReader.readLine();
				  System.out.println(line);
				  //catch bdaddr and send it to messageHandler
				  if(line.contains("bdaddr")){
					  log.putString("bdaddr",line);
					  break;
				  }
				 }
				Message bdaddr = new Message();
				bdaddr.setData(log);
				messageHandler.sendMessage(bdaddr);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.print(e.getStackTrace());
			}
			
		}
		
	};
	
	//method to set up the bluetooth device with given parameters
	private boolean initBluetoothDevice(String mac){
		Process process;
		try {
			//getting su
			process = Runtime.getRuntime().exec("su");
			//getting stin to write command in su shell
			DataOutputStream  stream=new DataOutputStream(process.getOutputStream());
			stream.writeBytes("cd /data/local/tmp"+"\n");
			stream.writeBytes("./hciconfig hci0 up"+"\n");
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			stream.writeBytes("./bdaddr -i hci0 -r -t "+mac+"\n");
			System.out.println("mac address : "+mac);
			stream.writeBytes("./hciconfig hci0 sspmode 0"+"\n");
			stream.writeBytes("./hciconfig hci0 class 0x10000"+"\n");
			stream.writeBytes("./hciconfig hci0 lm MASTER,ACCEPT"+"\n");
			stream.writeBytes("./hciconfig hci0 name LG"+"\n");
			stream.writeBytes("./hciconfig hci0 piscan"+"\n"); 
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.print(e.getStackTrace());
			return false;
		}
		return true;
		
	}
		
	private void displayToast(CharSequence text){
		Context context = getApplicationContext();
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
	}
	
	private String extractBdAddr(String addr){
		Pattern pattern = Pattern.compile("bdaddr (([0-9A-F]{2}:){5}[0-9A-F]{2})");
		Matcher matcher = pattern.matcher(addr);
		if(matcher.find()){
			return matcher.group(1);
		}
		else{
			return addr;	
		}
	}
	
}

